package com.seagox.chat.config;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.seagox.chat.chat.entity.ChatContact;
import com.seagox.chat.chat.entity.ChatMessage;
import com.seagox.chat.chat.entity.Message;
import com.seagox.chat.chat.mapper.ChatContactMapper;
import com.seagox.chat.chat.service.impl.ChatMessageService;

@Component
public class EventListenner {
	
	private static final Logger logger = LoggerFactory.getLogger(EventListenner.class);
	
    @Resource
    private ClientCache clientCache;
    
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    
    @Autowired
    private ChatMessageService chatMessageService;
    
    @Autowired
    private ChatContactMapper chatContactMapper;

    /**
     * 客户端连接
     *
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        if(!StringUtils.isEmpty(userId)) {
        	UUID sessionId = client.getSessionId();
            clientCache.saveClient(userId, sessionId, client);
            logger.info("建立连接:" + userId);
        }
    }

    /**
     * 客户端断开
     *
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        clientCache.deleteSessionClient(userId, client.getSessionId());
        client.disconnect();
        logger.info("关闭连接:" + userId);
    }

	/**
	 * 监听客户端事件chat
	 *
	 * @param client  客户端信息
	 * @param request 请求信息
	 * @param data    客户端发送数据
	 */
	@OnEvent("chat")
	public void onEevent(SocketIOClient client, AckRequest request, Message message) {
		message.setCreateTime(new Date());
		List<String> targetList = message.getTarget();
		targetList.remove(message.getSource());
		ChatContact chatContact = new ChatContact();
		chatContact.setType(message.getType());
		chatContact.setContent(message.getContent());
		chatContact.setUnread(0);
		chatContact.setMsgid(message.getMsgid());
		chatContact.setUpdateTime(new Date());
		if(message.getClassify() == 2) {
			chatContact.setTarget(message.getSource());
		}
		chatContactMapper.updateById(chatContact);
		LambdaQueryWrapper<ChatContact> qw = new LambdaQueryWrapper<>();
		qw.eq(ChatContact::getSessionId, message.getSessionId()).eq(ChatContact::getSource, message.getSource());
		chatContactMapper.update(chatContact, qw);
		chatContactMapper.updateContactByTalker(message, targetList);
		List<ChatMessage> chatMessageList = new ArrayList<>();
		targetList.add(message.getSource());
		List<String> finalList = message.getTarget();
		if(message.getClassify() == 3) {
			finalList.remove("0");
		}
		for (String target : finalList) {
			ChatMessage chatMessage = new ChatMessage();
			chatMessage.setContent(message.getContent());
			chatMessage.setType(message.getType());
			chatMessage.setUpdateTime(new Date());
			chatMessage.setSessionId(message.getSessionId());
			chatMessage.setSource(message.getSource());
			chatMessage.setTarget(target);
			if (message.getSource().equals(target)) {
				chatMessage.setReadTime(new Date());
			}
			chatMessage.setMsgid(message.getMsgid());
			chatMessageList.add(chatMessage);
		}
		chatMessageService.saveBatch(chatMessageList);
		redisTemplate.convertAndSend("chat", JSON.toJSONString(message));
	}
    
}

